package com.aosai.localtax.dao;


import com.aosai.localtax.model.MainViewPagerModel;
import com.squareup.okhttp.Response;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

import pw.hais.http.Http;
import pw.hais.http.base.OnHttpListener;
import pw.hais.utils.L;

/**
 * Created by Hais1992 on 2015/9/24.
 */
public class TaskDao {
    public static final String SERVER_URL_IMAGE = "http://www.gxds.gov.cn";

    /**
     * 获取图片列表
     */
    public static void getList(final OnHttpListener<List<MainViewPagerModel>> listener) {
        Http.get(SERVER_URL_IMAGE + "/index.html", null, new OnHttpListener<String>() {
            @Override
            public void onSuccess(Response response, String html) {
                doArticleHtmlToListModel(html, listener);
            }
        });
    }

    private static void doArticleHtmlToListModel(String html, OnHttpListener<List<MainViewPagerModel>> listener) {
        List<MainViewPagerModel> list = new ArrayList<>();
        Document document = Jsoup.parse(html);
        Elements elements = document.getElementsByClass("img-news-list").last().select("li");
        for (Element e : elements) {
            String image_url = e.select("img").attr("src");
            Element elemt = e.getElementsByClass("news-title").last().select("a").last();
            String url = elemt.attr("href");
            String title = elemt.text();
            MainViewPagerModel imageModel = new MainViewPagerModel();
            imageModel.title = title;
            imageModel.subTitle =  e.getElementsByClass("img-news-sub").select("p").text();
            imageModel.image_url = SERVER_URL_IMAGE + image_url;
            imageModel.url = SERVER_URL_IMAGE + url;
            list.add(imageModel);
            L.i(title + "-----------" + image_url);
        }
        if (listener != null) listener.onSuccess(null, list);
    }
}
